import React, { useState, useEffect, useCallback } from 'react';
import Taro, { useDidHide } from '@tarojs/taro';
import {AtIcon} from "taro-ui";
import {View, Swiper, Text, Image, SwiperItem, Block} from '@tarojs/components';
import {H5_VIDEO, TARO_ENV} from "../../../constants/api";
import './detail-header.scss';

const formatTime = (timeNum) => {
  const minus = Math.floor(timeNum / 60)
  const seconds = Math.floor(timeNum) % 60
  return {minus: minus > 9 ? minus : '0' + minus, seconds: seconds > 9 ? seconds : '0' + seconds}
}

let txv = ''

if (process.env.TARO_ENV === 'weapp') {
  try {
    txv = Taro.requirePlugin('tencentvideo')
  } catch (e) {
    txv = ''
  }
}

const TxvContext = process.env.TARO_ENV != 'h5' ? txv : '';
const audioCtx = Taro.createInnerAudioContext();
let txvContext: any = '';
const DetailHeader: ({pkeys, mp3, videoId, imagesList, height, mode}: { pkeys?: any; mp3?: any; videoId?: any; imagesList?: any; height?: any; mode?: any }) => void = ({pkeys = '', mp3 = '', videoId = '', imagesList = [], height = 0, mode = 'aspectFit'}) => {
  const [type, setType] = useState<'mp3' | 'image' | 'video'>('image');
  const [imageIndex, setImageIndex] = useState(0);
  const [playStatus, setPlayStatus] = useState(false);
  const [isMuted, setIsMuted] = useState(true);
  const [status, setStatus] = useState<'play' | 'pause' | 'end'>('pause');
  const [curTime, setCurTime] = useState('00:00');
  const [endTime, setEndTime] = useState('00:00');
  const [max, setMax] = useState(0);
  const [curValue, setCurValue] = useState(0);
  const [res, setRes] = useState<{ type: 'mp3' | 'image' | 'video'; data: string | string[] }[]>([]);
  const [translate, setTranslate] = useState(0);

  useEffect(() => {
    if (process.env.TARO_ENV === 'weapp') {
      audioCtx.onCanplay(() => {
        audioCtx.duration
        const timer = setTimeout(() => {
          const time = formatTime(audioCtx.duration)
          setEndTime(time.minus + ':' + time.seconds);
          setMax(Math.floor(audioCtx.duration));
          clearTimeout(timer)
        }, 1000)
      })
      audioCtx.onTimeUpdate(() => {
        const time = formatTime(audioCtx.currentTime)
        setCurTime(time.minus + ':' + time.seconds);
        setCurValue(Math.floor((audioCtx.currentTime / max) * 100));
      })
      audioCtx.onPlay(() => {
        setStatus('play');
        setPlayStatus(true)
      })
      audioCtx.onPause(() => {
        setStatus('pause');
        setPlayStatus(false)
      })
      audioCtx.onStop(() => {
        //console.log('stop')
      })
      audioCtx.onEnded(() => {
        setCurValue(0);
        setCurTime('00:00');
        setStatus('end');
      })
    }
  }, [max])

  useEffect(() => {
    if (videoId && process.env.TARO_ENV === "h5") {
      const el: any = document.querySelector('.myIframe')
      el.src = H5_VIDEO + videoId
    }
  }, [videoId])


  const changeType = useCallback((types) => {
    if (videoId && types != 'video') {
      if (txvContext) txvContext.pause();
    }
    if (videoId && types == 'video') {
      if (txvContext) txvContext.play();
    }
    if (types === 'mp3') {
      if (mp3) {
        audioCtx.play()
        setPlayStatus(true)
      }
    } else {
      mp3 && audioCtx.pause()
    }
    const index = res.findIndex(item => item.type === types)
    setTranslate(index || 0);
    setType(types)
  }, [mp3, res, videoId])

  useEffect(() => {
    audioCtx.src = mp3 || '';
    if (videoId && process.env.TARO_ENV === 'weapp') {
      txvContext = TxvContext && TxvContext.getTxvContext('myVideo');
    }
    const temp: any[] = [];
    if (videoId && process.env.TARO_ENV !== 'tt') temp.push({type: 'video', data: videoId || ''});
    if (imagesList) temp.push({type: 'image', data: imagesList || []});
    if (mp3) temp.push({type: 'mp3', data: mp3 || ''});
    if (temp && temp.length > 0) {
      setRes(temp)
      setTranslate(0)
      setType(temp[0].type)
    }
  }, [imagesList, mp3, videoId])

  useDidHide(() => {
    audioCtx.pause()
  })

  useEffect(() => {
    let timer
    if (TARO_ENV === 'h5' && imagesList && imagesList.length > 0 && pkeys) {
      // 1. 获取元素
      const focus: any = document.querySelector('.swiper-container');
      const ul = focus.children[0];
      // 获得focus 的宽度
      const w = focus.offsetWidth;
      // 2. 利用定时器自动轮播图图片
      let index = 0;
      if (imagesList.length > 1) {
        timer = setInterval(() => {
          index++;
          const translatex = -index * w;
          ul.style.transition = 'all .3s';
          ul.style.transform = 'translateX(' + translatex + 'px)';
        }, 5000);
      }
    }

    return () => {
      clearInterval(timer)
      audioCtx.stop()
    }
  }, [imagesList, pkeys])

  const swiperChange = (e) => {
    if (e.detail.current <= imagesList.length) {
      const index = e.detail.current || 0;
      setImageIndex(index);
    }
  }

  const play = () => {
    if (type === 'video') {
      if (playStatus) {
        txvContext.pause();
      } else {
        txvContext.play();
      }
      setPlayStatus(!playStatus);
    } else if (type === 'mp3') {
      if (playStatus) {
        audioCtx.pause()
      } else {
        audioCtx.play()
      }
      setPlayStatus(!playStatus)
    }
  }

  const previewImage = (urls, current) => {
    Taro.previewImage({
      current: current, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  }

  return (
    <View className='detail-header-box'>
      <View className='wrap' style={`transform: translate(-${100 * translate}vw);width: ${res.length * 100}vw;`}>
        {!!videoId && process.env.TARO_ENV !== 'tt' &&
        <View className={`item video-box video-box-${process.env.TARO_ENV}`}
              hidden={!videoId}
        >
          {process.env.TARO_ENV != 'h5' ?
            <Block>
              <txv-video
                width='100vw'
                height='100%'
                controls={false}
                loop
                muted={isMuted}
                className='video'
                vid={videoId}
                playerid='myVideo'
                object-fit='contain'
                autoplay
                isNeedMutex
                isHiddenStop
                showCenterPlayBtn={false}
                onPlay={() => {
                  setPlayStatus(true)
                }}
                onPause={() => {
                  setPlayStatus(false)
                }}
              >
              </txv-video>
              <View className={(!playStatus) ? "hide1 left" : "hide2 left"}>
                {playStatus &&
                <View className='zz' onClick={() => play()}> <Text className='at-icon icon at-icon-pause'/></View>}
                {(!playStatus) && <View className='zz' onClick={() => {
                  play()
                }}
                > <Text className='at-icon icon at-icon-play'/></View>}
              </View>
            </Block> :
            <iframe allowFullScreen width='100%' height={window.innerWidth * 0.75 + 'px'} className='myIframe'/>
          }
        </View>}
        {imagesList && imagesList.length > 0 && !pkeys && <View className='item photo-box'
                                                                style={`height:${height ? (process.env.TARO_ENV === 'h5' ? height / 46 : height) : (process.env.TARO_ENV === 'h5' ? 320 / 46 : 320)}${process.env.TARO_ENV === 'h5' ? 'rem' : 'rpx'};margin-top:0px;margin-bottom:0px`}
        >
          <Swiper className='swiper' current={imageIndex} onChange={(e) => {
            swiperChange(e)
          }}
          >
            {imagesList && imagesList.length > 0 && imagesList.map((item, index) => {
              return <SwiperItem className='swiperItem' key={index}>
                <Image className='img' src={item} mode={mode} onClick={previewImage.bind(this, imagesList, item)}/>
              </SwiperItem>
            })}
          </Swiper>
        </View>}
        {imagesList && imagesList.length > 0 && TARO_ENV === 'h5' && pkeys &&
        <View className='item photo-box' style={`height:${height / 46.9}rem;margin-top:0px;margin-bottom:0px`}>
          <View className='swiper-container-wrapper swiper' style='padding: 0px; overflow: hidden;'>
            <View className='swiper-container swiper-container-horizontal swiper-container-ios'
                  style='overflow: visible;'
            >
              <View className='swiper-wrapper'>
                {imagesList && imagesList.length > 0 && imagesList.map((item, index) => {
                  return <View className='swiper-slide swiperItem' style={'width: ' + window.innerWidth + 'px;'}
                               key={index}
                  ><Image className='img' src={item}/></View>
                })}
              </View>
            </View>
          </View>
        </View>}
        {mp3 && imagesList && imagesList[0] &&
        <View className='item sound-box' style={`background-image: url(${imagesList[0]})`}>
          <View className={`mp3-icon animation ${status === 'pause' ? 'stop' : ''} ${status === 'end' ? 'end' : ''}`}>
            <Text className='xxhz xxhz-music-rf' style='font-size:50px;'/>
          </View>
          {type === 'mp3' && <View className='overlay-image'/>}
        </View>}
      </View>
      <View className={`btn-box ${process.env.TARO_ENV} ${type + '-btn-box'}`}>
        <View className='position-r'>
          <View className='left'>
            {(type === 'mp3') && playStatus && <Text className='at-icon icon at-icon-pause' onClick={() => {
              play()
            }}
            />}
            {(type === 'mp3') && !playStatus && <Text className='at-icon icon at-icon-play' onClick={() => {
              play()
            }}
            />}
            {(type === 'video') && isMuted && process.env.TARO_ENV !== 'h5' &&
            <AtIcon value='icon icon-jingyin' size='24' onClick={() => {
              setIsMuted(false)
            }}
            />}
            {(type === 'video') && !isMuted && process.env.TARO_ENV !== 'h5' &&
            <AtIcon value='icon icon-shengyin' size='24' onClick={() => {
              setIsMuted(true)
            }}
            />}
          </View>
          <View className='center'>
            {res.length > 1 && res.map((item, index) => <Block key={index}>
              <View className={`btn-item ${type === item.type ? 'active' : ''}`} onClick={() => {
                changeType(item.type)
              }}
              >
                {item.type === 'video' && <Block><Text className='at-icon icon at-icon-video'/><Text>视频</Text></Block>}
                {item.type === 'image' && <Block><Text className='at-icon icon at-icon-image'/><Text>图册</Text></Block>}
                {item.type === 'mp3' && <Block><Text className='at-icon icon at-icon-sound'/><Text>讲解</Text></Block>}
              </View>
            </Block>)}
          </View>
          <View className='right'>
            {type === 'image' &&
            <Text className='image-number'>{imageIndex + 1}/{imagesList && imagesList.length || 0}</Text>}
            {process.env.TARO_ENV !== 'h5' && type === 'mp3' &&
            <Text className='image-number'>{curTime}/{endTime}</Text>}
          </View>
        </View>
      </View>
      {type !== 'video' && <View className='btn-bg'/>}
    </View>
  )
}

DetailHeader.config = {
  usingComponents: {
    "txv-video": "plugin://tencentvideo/video"
  }
}

DetailHeader.options = {
  addGlobalClass: true
}

export default DetailHeader
